<?php
/**
* @filename source_module.php 2013-11-11 02:10:56x
* @author Huming Xu <huming17@126.com>
* @version 1.0.0
* @copyright DZF (c) 2013, Huming Xu
*/

class ctrl_trade_course extends trade_course{
    public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
    
    static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}
    /*
	*	取出一条信息
	*/
	public function do_detail($tc_id='') {
        global $_G;
		$detail = array();
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
		$detail = $this->one_info('trade_course','tc_id',$tc_id);
        $course_info = self::get_field_value_by_id('course_main','cm_id',$detail['cm_id'],'cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num');
        $course_info=$course_info['cm_img'];
        unset($detail['create_dateline']);
        unset($detail['modify_dateline']);
        foreach($course_info AS $key=>$value){
            $detail[$key]=$value;
        }
        //DEBUG 获取课程信息
        //DEBUG 调试输出
        if($_G['gp_api']){
            $return['code'] = '0';
            $return['data'][$_G['gp_mod']][$_G['gp_action']][$_G['gp_do']]=$detail;
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }else{
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=trade&action=course&do=index&keyword=".$keyword);
            include template('trade/course/detail');
        }
	}
    
	/*
	*  添加系统信息
	*/
	public function do_add() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$trade_course = isset($_REQUEST['trade_course']) && !empty($_REQUEST['trade_course']) ? $_REQUEST['trade_course']:'';
		if('1'==$issubmit){
            //TODO 后端字段校验 根据具体业务逻辑添加
            //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
            foreach($trade_course AS $key => $value){
                if(is_array($value) && !empty($value)){
                    $trade_course[$key] = implode(",", $value);
                }
            }
            $trade_course['create_dateline'] = TIMESTAMP;
            $insert_id = $this->add('trade_course',$trade_course);
            if($insert_id){
                showmessage('操作成功','index.php?mod=trade&action=course&do=index');
            }else{
                showmessage('操作失败','index.php?mod=trade&action=course&do=index');
            }
		}else{
			include template('trade/course/add');
		}
	}
    
	/*
	*  编辑系统信息
	*/
	public function do_edit() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$trade_course = isset($_REQUEST['trade_course']) && !empty($_REQUEST['trade_course']) ? $_REQUEST['trade_course']:'';
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
        if($tc_id){
            if('1'==$issubmit){
                $trade_course['modify_dateline'] = TIMESTAMP;
                //DEBUG 判断是否数组字段,如果是数组转换为逗号间隔 字符串存贮
                foreach($trade_course AS $key => $value){
                    if(is_array($value) && !empty($value)){
                        $trade_course[$key] = implode(",", $value);
                    }
                }                
                $where = array('tc_id'=>$tc_id);
                $effect_row = $this->edit('trade_course',$trade_course,$where);
                if($effect_row){
                    showmessage('操作成功','index.php?mod=trade&action=course&do=index');
                }else{
                    showmessage('操作失败','index.php?mod=trade&action=course&do=index');
                }
            }else{
                //DEBUG 获取操作对象信息
                $info = $this->one_info('trade_course','tc_id',$tc_id);
                include template('trade/course/edit');
            }
        }else{
            showmessage('请选择编辑对象','index.php?mod=trade&action=course&do=index');
        }
	}
    
	/*
	*  删除系统信息
	*/
	public function do_delete() {
        global $_G;
        $tc_id = isset($_REQUEST['tc_id']) ? $_REQUEST['tc_id'] : '';
        if($tc_id){
            $effect_row = $this->delete("trade_course", array("tc_id" => $tc_id), $limit=1);
            if($effect_row){
                showmessage('操作成功','index.php?mod=trade&action=course&do=index');
            }else{
                showmessage('操作失败','index.php?mod=trade&action=course&do=index');
            }
        }
    }
	/*
	*  系统信息列表
	*/
	public function do_index(){
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $default_limit=20;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
        $start=(($page-1) * $perpage);
        $wheresql = " AND user_id='".$_G['user_id']."' AND tc_flag=2 AND isdelete = 0 ";
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        if(!$_G['user_id']){
        	$noauth = [
        			'code'=>'10000',
        			'msg'=>lang('core','noauth'),
        			'data'=>[]
        	];
        	echo json_encode($noauth,JSON_FORCE_OBJECT);return false;
        	 
        }
        if($keyword){
            $wheresql = " AND user_id LIKE '%".$keyword."%' ";
        }
        $orderby = " ORDER BY tc_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $total_rows,
            //array 一页数据数组
            'page_data' => $page_data 
        );
        */
        $page_result = $this->course_index('trade_course',$page_condition);
        foreach($page_result['page_data'] AS $key => $value){
            $page_result['page_data'][$key]=$value['cm_id'];
            $page_result['page_data_tmp'][$value['cm_id']]['nowClass']=$value['nowClass'];
            $page_result['page_data_tmp'][$value['cm_id']]['classTime']=$value['classTime'];
        }
        $course_res = self::get_field_value_by_id('course_main','cm_id',$page_result['page_data'],'cm_cate_id,cm_start_time,cm_brief,cm_id,cm_name,cm_brief,cm_img,cm_price,cm_count,so_id,so_id,cm_hour_num,create_dateline,is_group');       
        $page_result['page_now']=$page;
        $page_result['total_page']=max(1, ceil(count($course_res)/$perpage));
        //int 返回结果总数
        $page_result['total_rows'] = count($course_res);
        //组合课程和普通课程手动分页
        $totalRows = count($sql_result);
        $newRes = array_chunk($course_res , $limit);
        
        $course_info = $newRes[$page - 1];
        
        unset($page_result['page_data']);
        $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
        if($client=='pc'){
            foreach($course_info AS $key=>$value){
                $tmp=array();
                $tmp['type'] = $value['cm_cate_id'];
                $tmp['startTime'] = date('Y-m-d',$value['cm_start_time']);
                $tmp['title'] = $value['cm_name'];
                $tmp['price'] = $value['cm_price'];
                $tmp['school'] = $this->get_field_value_by_id('school_online','so_id',$value['so_id'],'so_name');
                $tmp['id'] = $value['cm_id'];
                $tmp['img'] = $value['cm_img'];
                $tmp['info'] = $value['cm_brief'];
                $tmp['times'] = $value['cm_hour_num'];
                $page_result['page_data'][]=$tmp;
            }   
        }else{
            foreach($course_info AS $key=>$value){
                $value['nowClass']=$page_result['page_data_tmp'][$value['cm_id']]['nowClass'];
                $value['classTime']=$page_result['page_data_tmp'][$value['cm_id']]['classTime'];
                $value['so_name'] = $this->get_field_value_by_id('school_online','so_id',$value['so_id'],'so_name');
                $page_result['page_data'][]=$value;
            }  
        }
        unset($page_result['page_data_tmp']);
        //DEBUG 获取课程信息
        
        if($page_result){
            $return['code'] = '0';
            $return['data'][$_G['gp_mod'].'_'.$_G['gp_action'].'_'.$_G['gp_do']]=$page_result;
            if($client=='pc'){
                $return['data']=$page_result;
            }else{
                $return['data'][$_G['gp_mod'].'_'.$_G['gp_action'].'_'.$_G['gp_do']]=$page_result;
            }
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }
	}
    
    /*
	*  系统信息列表
	*/
	public function do_calendar(){
        global $_G;
        //DEBUG 设定今日时间范围
        $today = date('Y-m-d',TIMESTAMP);
        $today_start_time = strtotime($today." 00:00:00");
        $today_end_time = strtotime($today." 23:59:59");
        //DEBUG 取出今日已开始未结束的课程
        $default_limit=100;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
        $start=(($page-1) * $perpage);
        $wheresql = " AND cm_start_time < '".$today_start_time."' AND cm_end_time > '".$today_end_time."' ";
        $orderby = " ORDER BY cm_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        $page_result = $this->index('course_main',$page_condition);
        $course_main = $cm_ids = array();
        foreach($page_result['page_data'] AS $key => $value){
            $cm_ids[$value['cm_id']]=$value['cm_id'];
            $course_main[$value['cm_id']]=$value;
        }
        //DEBUG 过滤我购买的所有课程 开始 //TODO 逻辑优化
        $default_limit=100;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
        $start=(($page-1) * $perpage);
        $wheresql = " AND tc_flag =2 AND cm_id IN (".dimplode($cm_ids).") ";
        $orderby = "";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        $page_result = $this->index('trade_course',$page_condition);
        $trade_course_cm_ids = array();
        foreach($page_result['page_data'] AS $key => $value){
            $trade_course_cm_ids[$value['cm_id']]=$value['cm_id'];
        }
        //DEBUG 过滤我购买的所有课程 结束 //TODO 逻辑优化
        //DEBUG 取出今日课程 有上课的课时
        $default_limit=100;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : $default_limit;
        $start=(($page-1) * $perpage);
        $wheresql = " AND ch_start_time > '".$today_start_time."' AND ch_end_time < '".$today_end_time."' AND cm_id IN (".dimplode($trade_course_cm_ids).") ";
        $orderby = " ORDER BY ch_start_time ASC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        $page_result = $this->index('course_hour',$page_condition);
        $course_hour = array();
        //{ title: '交互设计流程解析-百度魔图案例', teacher: '王老师', startTime: '09-11 13:00', lastTime: '00:45:00', id: '1', course: { id: '1', title: 'C++程序设计', type: '1', img: '/images/310.png' } },
        foreach($page_result['page_data'] AS $key => $value){
            $tmp['title']=$value['ch_name'];
            $tmp['teacher']=ext::user_realname($value['ch_teacher_id']);
            $tmp['startTime']=date('m-d H:i',$value['ch_start_time']);
            $tmp['lastTime']=date('H:i:s',$value['ch_end_time']);
            $tmp['id']=$value['ch_id'];
            $tmp['course']['id']=$course_main[$value['cm_id']]['cm_id'];
            $tmp['course']['title']=$course_main[$value['cm_id']]['cm_name'];
            $tmp['course']['type']=$course_main[$value['cm_id']]['cm_cate_id'];
            $tmp['course']['img']=$course_main[$value['cm_id']]['cm_img'];
            $course_hour[]=$tmp;
        }
        $client = isset($_REQUEST['client']) ? $_REQUEST['client'] : 'wap';
        if($_G['gp_api']){
            $return['code'] = '0';
            $return['data']=$course_hour;
            echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
        }else{
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=trade&action=course&do=index&keyword=".$keyword);
            include template('trade/course/index');	 
        }
	}
    
   /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $return_type string json/xml.
     *
     * @return print string json/xml.
     */
	public function do_api(){
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start=(($page-1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if($keyword){
            $wheresql = " WHERE title LIKE '%".$keyword."%'";
        }
        $orderby = " ORDER BY tc_id DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition=array(
            'page' => $page,//int 请求页面 页码
            'limit' => $limit,//int 每页请求个数
            'perpage' => $perpage,//int 每页显示个数
            'wheresql' => $wheresql,//string //条件SQL语句 
            'orderby' => $orderby,//string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
        $page_result = array(
            //int 返回结果总数
            'total_rows' => $total_rows,
            //array 一页数据数组
            'page_data' => $page_data 
        );
        */
        $page_result = $this->api('trade_course',$page_condition);      
        if('json'==$return_type){
            $return = json_encode($page_result);	
        }elseif('xml'==$return_type){
            $return = array2xml($page_result);
        }
        //DEBUG 接口响应直接输出返回
		echo $return;
	}
}
?>